<?php

// 应用公共文件
/**
 * 默认生成10位长度的加密盐值
 * @param string $salt
 * @param number $length
 * @return string
 */
function create_salt($salt='',$length = 10){
	if (empty($salt)){
		$salt = mt_rand(100,9999).microtime(true);
	}
	return mb_substr(crypt(mt_rand(100000,999999),$salt), 0,$length);
}

/**
 * 密码字符串
 * @param string $password
 * @param string $salt
 * @param number $saltGain
 * @return string
 */
function optimizedSaltPwd($password, $salt, $saltGain = 1){
	//过滤参数
	if(!is_numeric($saltGain)) exit;
	if(intval($saltGain) < 0 || intval($saltGain) > 35) exit;
	//对Md5盐值进行变换
	$tempSaltMd5 = md5($salt);
	for($i = 0;$i < strlen($tempSaltMd5);$i ++){
		if(ord($tempSaltMd5[$i]) < 91 && ord($tempSaltMd5[$i]) > 32){
			$tempSaltMd5[$i] = chr(ord($tempSaltMd5[$i]) + $saltGain);
		}
	}
	//计算哈希值
	$tempPwdMd5 = md5($password);
	return sha1($tempSaltMd5 . $tempPwdMd5 . strrev($tempSaltMd5));
}

function p($arr){
	echo '<pre>';
	print_r($arr);
	echo '</pre>';
}

/**
 * 获取客户端操作系统信息包括win10
 * @author  Jea杨
 * @return string
 */
function getOs(){
	$agent = $_SERVER['HTTP_USER_AGENT'];
	
	if (preg_match('/win/i', $agent) && strpos($agent, '95')) {
		$os = 'Windows 95';
	} else if (preg_match('/win 9x/i', $agent) && strpos($agent, '4.90')) {
		$os = 'Windows ME';
	} else if (preg_match('/win/i', $agent) && preg_match('/98/i', $agent)) {
		$os = 'Windows 98';
	} else if (preg_match('/win/i', $agent) && preg_match('/nt 6.0/i', $agent)) {
		$os = 'Windows Vista';
	} else if (preg_match('/win/i', $agent) && preg_match('/nt 6.1/i', $agent)) {
		$os = 'Windows 7';
	} else if (preg_match('/win/i', $agent) && preg_match('/nt 6.2/i', $agent)) {
		$os = 'Windows 8';
	} else if (preg_match('/win/i', $agent) && preg_match('/nt 10.0/i', $agent)) {
		$os = 'Windows 10';#添加win10判断
	} else if (preg_match('/win/i', $agent) && preg_match('/nt 5.1/i', $agent)) {
		$os = 'Windows XP';
	} else if (preg_match('/win/i', $agent) && preg_match('/nt 5/i', $agent)) {
		$os = 'Windows 2000';
	} else if (preg_match('/win/i', $agent) && preg_match('/nt/i', $agent)) {
		$os = 'Windows NT';
	} else if (preg_match('/win/i', $agent) && preg_match('/32/i', $agent)) {
		$os = 'Windows 32';
	} else if (preg_match('/linux/i', $agent)) {
		$os = 'Linux';
	} else if (preg_match('/unix/i', $agent)) {
		$os = 'Unix';
	} else if (preg_match('/sun/i', $agent) && preg_match('/os/i', $agent)) {
		$os = 'SunOS';
	} else if (preg_match('/ibm/i', $agent) && preg_match('/os/i', $agent)) {
		$os = 'IBM OS/2';
	} else if (preg_match('/Mac/i', $agent)) {
		$os = 'Mac';
	} else if (preg_match('/PowerPC/i', $agent)) {
		$os = 'PowerPC';
	} else if (preg_match('/AIX/i', $agent)) {
		$os = 'AIX';
	} else if (preg_match('/HPUX/i', $agent)) {
		$os = 'HPUX';
	} else if (preg_match('/NetBSD/i', $agent)) {
		$os = 'NetBSD';
	} else if (preg_match('/BSD/i', $agent)) {
		$os = 'BSD';
	} else if (preg_match('/OSF1/i', $agent)) {
		$os = 'OSF1';
	} else if (preg_match('/IRIX/i', $agent)) {
		$os = 'IRIX';
	} else if (preg_match('/FreeBSD/i', $agent)) {
		$os = 'FreeBSD';
	} else if (preg_match('/teleport/i', $agent)) {
		$os = 'teleport';
	} else if (preg_match('/flashget/i', $agent)) {
		$os = 'flashget';
	} else if (preg_match('/webzip/i', $agent)) {
		$os = 'webzip';
	} else if (preg_match('/offline/i', $agent)) {
		$os = 'offline';
	} elseif (preg_match('/ucweb|MQQBrowser|J2ME|IUC|3GW100|LG-MMS|i60|Motorola|MAUI|m9|ME860|maui|C8500|gt|k-touch|X8|htc|GT-S5660|UNTRUSTED|SCH|tianyu|lenovo|SAMSUNG/i', $agent)) {
		$os = 'mobile';
	} else {
		$os = '未知操作系统';
	}
	return $os;
}

/**
 * 获取客户端浏览器信息 添加win10 edge浏览器判断
 * @author  Jea杨
 * @return string
 */
function getBroswer(){
	$sys = $_SERVER['HTTP_USER_AGENT'];  //获取用户代理字符串
	if (stripos($sys, "Firefox/") > 0) {
		preg_match("/Firefox\/([^;)]+)+/i", $sys, $b);
		$exp[0] = "Firefox";
		$exp[1] = $b[1];  //获取火狐浏览器的版本号
	} elseif (stripos($sys, "Maxthon") > 0) {
		preg_match("/Maxthon\/([\d\.]+)/", $sys, $aoyou);
		$exp[0] = "傲游";
		$exp[1] = $aoyou[1];
	} elseif (stripos($sys, "MSIE") > 0) {
		preg_match("/MSIE\s+([^;)]+)+/i", $sys, $ie);
		$exp[0] = "IE";
		$exp[1] = $ie[1];  //获取IE的版本号
	} elseif (stripos($sys, "OPR") > 0) {
		preg_match("/OPR\/([\d\.]+)/", $sys, $opera);
		$exp[0] = "Opera";
		$exp[1] = $opera[1];
	} elseif (stripos($sys, "Edge") > 0) {
		//win10 Edge浏览器 添加了chrome内核标记 在判断Chrome之前匹配
		preg_match("/Edge\/([\d\.]+)/", $sys, $Edge);
		$exp[0] = "Edge";
		$exp[1] = $Edge[1];
	} elseif (stripos($sys, "Chrome") > 0) {
		preg_match("/Chrome\/([\d\.]+)/", $sys, $google);
		$exp[0] = "Chrome";
		$exp[1] = $google[1];  //获取google chrome的版本号
	} elseif (stripos($sys, 'rv:') > 0 && stripos($sys, 'Gecko') > 0) {
		preg_match("/rv:([\d\.]+)/", $sys, $IE);
		$exp[0] = "IE";
		$exp[1] = $IE[1];
	} elseif (stripos($sys, 'Safari') > 0) {
		preg_match("/safari\/([^\s]+)/i", $sys, $safari);
		$exp[0] = "Safari";
		$exp[1] = $safari[1];
	} else {
		$exp[0] = "未知浏览器";
		$exp[1] = "";
	}
	return $exp[0] . '(' . $exp[1] . ')';
}


/**
 * 是否存在方法
 * @param string $module 模块
 * @param string $controller 待判定控制器名
 * @param string $action 待判定控制器名
 * @return number 方法结果，0不存在控制器 1存在控制器但是不存在方法 2存在控制和方法
 */
function has_action($module,$controller,$action)
{
	$arr=\ReadClass::readDir(APP_PATH . $module. DS .'controller');
	if((!empty($arr[$controller])) && $arr[$controller]['class_name']==$controller ){
		$method_name=array_map('array_shift',$arr[$controller]['method']);
		if(in_array($action, $method_name)){
			return 2;
		}else{
			return 1;
		}
	}else{
		return 0;
	}
}

/**
 * 强制下载
 * @param string $filename
 * @param string $content
 */
function download_content($filename, $content){
	header("Pragma: public");
	header("Expires: 0");
	header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
	header("Content-Type: application/force-download");
	header("Content-Transfer-Encoding: binary");
	header("Content-Disposition: attachment; filename=$filename");
	echo $content;
	exit();
}

/**
 * 返回数据表的sql
 * @param $table : 含前缀的表名
 * @return string
 */
function table_insert_sql($table){
	//设置防止页面超时
	if (function_exists('set_time_limit')){
		set_time_limit(0);
	}
	ignore_user_abort(true);
	@ini_set('memory_limit', '-1');
	
	$db_prefix =config('database.prefix');
	$export_sqls = array();
	$export_sqls [] = "DROP TABLE IF EXISTS $table";
	switch (config('database.type')) {
		case 'mysql' :
			if (!($createTable = db()->query("SHOW CREATE TABLE $table"))) {
				$this->error("'SHOW CREATE TABLE $table' Error!");
			}
			$table_create_sql = $createTable[0]['Create Table'];
			$export_sqls [] = $table_create_sql;
			$data_rows = db()->query("SELECT * FROM $table");
			$data_values = array();
			foreach ($data_rows as &$v) {
				foreach ($v as &$vv) {
					$vv = "'" . addslashes(str_replace(array("\r","\n"),array('\r','\n'),$vv)) . "'";
				}
				$data_values [] = '(' . join(',', $v) . ')';
			}
			if (count($data_values) > 0) {
				$export_sqls [] = "INSERT INTO `$table` VALUES \n" . join(",\n", $data_values);
			}
			break;
	}
	return join(";\n", $export_sqls) . ";";
}

/**
 * 邮件发送函数
 * @param string toUser      收件人
 * @param string title 邮件标题
 * @param string content 邮件内容
 * @return array
 */
function SendMail($toUser, $title, $content,$config = array(),$attachment = null) {
	if (empty($config)){
		$email = db('system')->where(array('name' => 'email_config'))->find();
		$email['value'] = unserialize($email['value']);
		if (!$email['value']['open_email']) return false;
		$config = $email['value'];
	}
	require_once EXTEND_PATH.DS.'PHPMailer'.DS.'smtp.class.php';
	require_once EXTEND_PATH.DS.'PHPMailer'.DS.'phpmailer.class.php';
	$mail = new \phpmailer();
	$mail->IsSMTP();
	$mail->SMTPDebug = 0;
	$mail->Host = $config['smtp_host'];
	$mail->SMTPAuth = true;
	//$mail->SMTPSecure = 'ssl'; //tls
	$mail->Username = $config['smtp_user'];
	$mail->Password = $config['smtp_pass'];
	$mail->CharSet = 'utf-8';
	$mail->Port = $config['smtp_port'];
	// 装配邮件头信息
	$mail->From = $config['from_email'];
	$mail->FromName = $config['from_name'];
	//$mail->SetFrom($config['from_email'],$config['from_name']);
	if (!empty($config['reply_email']) && !empty($config['reply_name'])){
		$mail->AddReplyTo($config['reply_email'],$config['reply_name']);
	}
	$mail->AddAddress($toUser);
	$mail->IsHTML(true);
	$mail->Subject = $title;
	$mail->Body = $content;
	if (is_array($attachment) && !empty($attachment)){
		foreach ($attachment as $file){
			is_file($file) && $mail->AddAttachment($file);
		}
	}
	// 发送邮件
	if ($mail->Send()){
		return true;
	}else{
		return $mail->ErrorInfo;
	}
}

/**
 * 发送短信方法
 */
function SendMobile($mobile,$content){
	
	$time = strtotime(date('Y-m-d'));
	$ip = request()->ip();
	$db = db('sms_log');
	$count = $db->where(array('mobile' => $mobile,'time' => array('GT',$time)))->count();
	if ($count >= config('send_num')) return array('status' => 0,'msg' => "发送短信超量");
	$count = $db->where(array('ip' => $ip,'time' => array('GT',$time)))->count();
	if ($count >= config('send_num')) return array('status' => 0,'msg' => "发送短信超量");
	
	if(!$mobile){
		return array('status' => 0,'msg' => "手机号码不能为空！");
	}
	if(!$content){
		return array('status' => 0,'msg' => "短信内容不能为空！");
	}
	$smsConfig = db('system')->where(array('name' => 'sms_config'))->find();
	$smsConfig['value'] = unserialize($smsConfig['value']);
	if (!$smsConfig['value']['open_sms']) {
		return array('status' => 0,'msg' => "短信功能未开启");
	}
	$smsConfig = $smsConfig['value'];
	$sends = new Sms($smsConfig['uid'],$smsConfig['mid'],$smsConfig['mpass']);
	//返回0发送成功
	if ($sends->sendSms($content,$mobile) == 0){
		return array('status' => 1,'msg' => '验证码发送成功');
	}else{
		return array('status' => 0,'msg' => '验证码发送失败');
	}
}

define('UC_KEY', '27a7UgRTVAkJVlMFAVNdAVIMB1wFV1NTUFABBAdXUwEGJ1AncSETcHgnMmB4czRdPW0DI2ZhUnw3dmksIiFCdnMzNwZSNg9VeDMlcFdxCW8hblUJYXE1QihjVFA3MnNuYTc3CnEnNXhsIDVddGcJdxVDwF2YTVoKmJuCQUzYFBuNzQabjQyCGgwNQVrY1QBNXkPCnJuU3wBZEAOITBZU3k0CSxmNDFYDQhWXxlMHMAbgxUc2M2aD5nbVEvMmdbdTE0NFEyVFV1NQ8MfWAOewBgVTBTZDVWL3IIJzQ9BXlmITQ0bicleA');//整合程序的通讯密钥  
/*加密解密 ENCODE 加密   DECODE 解密*/
function _encrypt($string, $operation = 'ENCODE', $key = '', $expiry = 0){
	if($operation == 'DECODE') {
		$string =  str_replace('_', '/', $string);
	}
	$key_length = 9;
	$key = md5($key != '' ? $key : UC_KEY);
	$fixedkey = md5($key);
	$egiskeys = md5(substr($fixedkey, 16, 16));
	$runtokey = $key_length ? ($operation == 'ENCODE' ? substr(md5(microtime(true)), -$key_length) : substr($string, 0, $key_length)) : '';
	$keys = md5(substr($runtokey, 0, 16) . substr($fixedkey, 0, 16) . substr($runtokey, 16) . substr($fixedkey, 16));
	$string = $operation == 'ENCODE' ? sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$egiskeys), 0, 16) . $string : base64_decode(substr($string, $key_length));
	
	$i = 0; $result = '';
	$string_length = strlen($string);
	for ($i = 0; $i < $string_length; $i++){
		$result .= chr(ord($string{$i}) ^ ord($keys{$i % 32}));
	}
	if($operation == 'ENCODE') {
		$retstrs =  str_replace('=', '', base64_encode($result));
		$retstrs =  str_replace('/', '_', $retstrs);
		return $runtokey.$retstrs;
	} else {
		if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$egiskeys), 0, 16)) {
			return substr($result, 26);
		} else {
			return '';
		}
	}
}


/*手机号码验证*/
function _checkmobile($mobilephone=''){
	if(strlen($mobilephone)!=11){
		return false;
	}
	if(preg_match("/^13[0-9]{1}[0-9]{8}$|15[0-9]{1}[0-9]{8}$|17[0-9]{1}[0-9]{8}$|14[0-9]{1}[0-9]{8}$|18[0-9]{1}[0-9]{8}$/",$mobilephone)){
		return true;
	}else{
		return false;
	}
}

/*邮箱验证*/
function _checkemail($email=''){
	if(mb_strlen($email)<5){
		return false;
	}
	$res="/^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/";
	if(preg_match($res,$email)){
		return true;
	}else{
		return false;
	}
}

/**
 * 判断是否为合法的身份证号码
 * @param $mobile
 * @return int
 */
function isCreditNo($vStr){
	$vCity = array(
		'11','12','13','14','15','21','22',
		'23','31','32','33','34','35','36',
		'37','41','42','43','44','45','46',
		'50','51','52','53','54','61','62',
		'63','64','65','71','81','82','91'
	);
	if (!preg_match('/^([\d]{17}[xX\d]|[\d]{15})$/', $vStr)) return false;
	if (!in_array(substr($vStr, 0, 2), $vCity)) return false;
	$vStr = preg_replace('/[xX]$/i', 'a', $vStr);
	$vLength = strlen($vStr);
	if ($vLength == 18) {
		$vBirthday = substr($vStr, 6, 4) . '-' . substr($vStr, 10, 2) . '-' . substr($vStr, 12, 2);
	} else {
		$vBirthday = '19' . substr($vStr, 6, 2) . '-' . substr($vStr, 8, 2) . '-' . substr($vStr, 10, 2);
	}
	if (date('Y-m-d', strtotime($vBirthday)) != $vBirthday) return false;
	if ($vLength == 18) {
		$vSum = 0;
		for ($i = 17 ; $i >= 0 ; $i--) {
			$vSubStr = substr($vStr, 17 - $i, 1);
			$vSum += (pow(2, $i) % 11) * (($vSubStr == 'a') ? 10 : intval($vSubStr , 11));
		}
		if($vSum % 11 != 1) return false;
	}
	return true;
}

function get_system_info($key){
	$system = db('system')->where(array('name' => $key))->find();
	if(!empty($system))
	return $system['value'];
}

/**
 * 递归子节点
 * @param array $data
 * @param number $parentid
 * @return array
 */
function getChild($data = array(),$parentid = 0){
	$array = array();
	foreach ($data as $key => $value){
		if ($value['parentid'] == $parentid){
			$value['child'] = getChild($data,$value['id']);
			$array[] = $value;
		}
	}
	return $array;
}

/**
 * 递归到最顶级
 * @param array $data
 * @param unknown $parentid
 * @return unknown
 */
function getParent($data = array(),$parentid){
	foreach ($data as $key => $value){
		if ($value['id'] == $parentid){
			if ($value['parentid']){
				return getParent($data,$value['parentid']);
			}else{
				return $value;
			}
		}
	}
}

/**
 * https请求（支持GET和POST）
 * @param $url
 * @param string $data
 * @return mixed
 */
function https_request($url, $data = null){
	$curl = curl_init();
	curl_setopt($curl, CURLOPT_URL, $url);
	curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
	curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
	//如果$data不是空使用POST
	if (!empty($data)){
		curl_setopt($curl, CURLOPT_POST, 1);
		curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
	}
	curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
	$output = curl_exec($curl);
	curl_close($curl);
	return $output;
}



/**
 *	短时间显示, 几分钟前,几秒前...
 **/
function _put_time($time = 0,$test=''){
	if(empty($time)){return $test;}
	$time = substr($time,0,10);
	$ttime = time() - $time;
	if($ttime <= 0 || $ttime < 60){
		return '几秒前';
	}
	if($ttime > 60 && $ttime <120){
		return '1分钟前';
	}
	
	$i = floor($ttime / 60);							//分
	$h = floor($ttime / 60 / 60);						//时
	$d = floor($ttime / 86400);							//天
	$m = floor($ttime / 2592000);						//月
	$y = floor($ttime / 60 / 60 / 24 / 365);			//年
	if($i < 30){
		return $i.'分钟前';
	}
	if($i > 30 && $i < 60){
		return '一小时内';
	}
	if($h>=1 && $h < 24){
		return $h.'小时前';
	}
	if($d>=1 && $d < 30){
		return $d.'天前';
	}
	if($m>=1 && $m < 12){
		return $m.'个月前';
	}
	if($y){
		return $y.'年前';
	}
	return "";
	
}
/**
 *	计算两经纬度之间的距离（km）
 **/
function getDistance($lat1, $lng1, $lat2, $lng2, $len_type = 2, $decimal = 2)
{

    $EARTH_RADIUS = 6378.137;
    $PI = 3.1415926;
    $radLat1 = $lat1 * $PI / 180.0;
    $radLat2 = $lat2 * $PI / 180.0;
    $a = $radLat1 - $radLat2;
    $b = ($lng1 * $PI / 180.0) - ($lng2 * $PI / 180.0);
    $s = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2)));
    $s = $s * $EARTH_RADIUS;
    $s = round($s * 1000);
    if ($len_type > 1) {
        $s /= 1000;
    }
    return round($s, $decimal);
}
/**
 *	根据距离返回对应配送设置
 **/
function delivery_config($actual_distance){
	// ajaxReturn(array('status' => 'success','data' => '12'));
	$string = db('system')->where('name','delivery_config')->value('value');
	// p($string);
	$arr = unserialize($string);
	$min_num = 99999999;
	$min_num_key = '';
	$max_num = 0;
	$max_num_key = '';
	$istrue = false;
	foreach ($arr as $key => $value) {
		if ($actual_distance <= $value['go_distance']) {
			$istrue = true;
			if ($value['go_distance'] <= $min_num) {
				$min_num = $value['go_distance'];
				$min_num_key = $key;
			}
		}else {
			if ($value['go_distance'] >= $max_num) {
				$max_num = $value['go_distance'];
				$max_num_key = $key;
			}
		}
	}
	if ($istrue) {
		return $arr[$min_num_key];
	}else{
		return $arr[$max_num_key];
	}
}

function delivery_user_config($actual_distance){
	$string = db('system')->where('name','delivery_user_config')->value('value');
	$arr = unserialize($string);
	$min_num = 99999999;
	$min_num_key = '';
	$max_num = 0;
	$max_num_key = '';
	$istrue = false;
	foreach ($arr as $key => $value) {
		if ($actual_distance <= $value['go_distance']) {
			$istrue = true;
			if ($value['go_distance'] <= $min_num) {
				$min_num = $value['go_distance'];
				$min_num_key = $key;
			}
		}else {
			if ($value['go_distance'] >= $max_num) {
				$max_num = $value['go_distance'];
				$max_num_key = $key;
			}
		}
	}
	if ($istrue) {
		return $arr[$min_num_key];
	}else{
		return $arr[$max_num_key];
	}
}

function subMoney($MoenyCount){
	return substr(sprintf("%.3f",$MoenyCount),0,-1);
}